package com.test.socket.handler;

import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import java.security.Principal;
import java.util.Collections;

/**
 * @author zxs
 * @since 2021/6/18
 */
@AllArgsConstructor
public class WebSocketConnectHandler  implements ApplicationListener<SessionConnectEvent> {

    private final SimpMessageSendingOperations messagingTemplate;

    @Override
    public void onApplicationEvent(SessionConnectEvent event) {
        System.out.println("connect....");
        MessageHeaders headers = event.getMessage().getHeaders();
        Principal user = SimpMessageHeaderAccessor.getUser(headers);
        if (user == null) {
            return;
        }
        //记录上线时间
        //String id = SimpMessageHeaderAccessor.getSessionId(headers);
        //this.repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
        //向好友推送上线消息
        this.messagingTemplate.convertAndSend("/topic/friends/signin", Collections.singletonList(user.getName()));
    }
}
